package com.mymoney.auth;

import java.io.IOException;

import javax.persistence.EntityNotFoundException;

import com.mymoney.beans.DeviceBean;
import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;

public class DeviceContext {

	private String applicationName = null;
	private String applicationVersion = null;
	private DeviceBean device = null;
	
	/**
	 * 
	 * @return
	 */
	public String getApplicationName() {
		return applicationName;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getApplicationVersion() {
		return applicationVersion;
	}
	
	/**
	 * 
	 * @return
	 */
	public DeviceBean getDevice() {
		return device;
	}
	
	/**
	 * 
	 * @param persistenceContext
	 * @param userAgent
	 * @param from
	 * @return
	 * @throws IOException
	 * @throws MyMoneyException
	 */
	public static DeviceContext createDeviceContext(PersistenceContext persistenceContext, 
			String primaryAccount) 
			throws IOException, MyMoneyException {
			
		DeviceContext context = new DeviceContext();
		
		if (primaryAccount != null) {
			DeviceBean device = null;		
			try {
				device = persistenceContext.getDeviceManager().getByName(primaryAccount);
			} catch (EntityNotFoundException e) {
				device = null;
			}
			if (device == null) {
				throw new MyMoneyException("Invalid Device!");
			}
			context.device = device;
		}
		return context;				
	}
}
